package com.snake.springboot.custom.service.impl.fileoss;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.snake.springboot.custom.api.model.fileoss.*;
import com.snake.springboot.custom.api.response.fileoss.OSSPoliciesRsp;
import com.snake.springboot.custom.api.service.fileoss.OSSService;
import com.snake.springboot.custom.service.config.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snake.common.date.DateUtil;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * <p>阿里云OSS业务
 * 类{@code AliOssImpl} </br>
 * 创建时间2025/5/8 9:53
 * @author yangxt
 * @see
 */
@Service
public class OSSAliServiceImpl implements OSSService {

    private Logger logger = LoggerFactory.getLogger(OSSAliServiceImpl.class);

    @Override
    public String ossType() {
        return OSSType.ALI_OSS.getCode();
    }

    @Override
    public OSSPoliciesRsp generatePolicies(String fileUrl, FileOSSModel ossModel) {
        OSSClient ossClient = initOSSClient(ossModel);
        try {
            String filepath=fileUrl;
             fileUrl = fileUrl.substring(1);
            long maxAge=1000*300;
            long contentLength=0;
            long endTime = System.currentTimeMillis() + maxAge;
            Date expiration = new Date(endTime);
            PolicyConditions conditions = new PolicyConditions();
            if (fileUrl != null) {
                conditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, fileUrl);
            }
            if (contentLength > 0) {
                conditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, contentLength);
            }
            String policy = ossClient.generatePostPolicy(expiration, conditions);
            byte[] bytes = policy.getBytes(StandardCharsets.UTF_8);
            String encodedPolicy = BinaryUtil.toBase64String(bytes);
            String signature = ossClient.calculatePostSignature(policy);
            OSSPoliciesRsp ossRsp=new OSSPoliciesRsp();
            ossRsp.setPolicy(encodedPolicy);
            ossRsp.setSignature(signature);
            ossRsp.setExpire(String.valueOf(endTime / 1000));
            ossRsp.setHost(ossModel.getCurl());
            ossRsp.setDir(fileUrl);
            ossRsp.setFilePath(filepath);
            return ossRsp;
        }catch ( Exception e){
            logger.error("阿里云OSS生成签名失败:",e);
        }finally {
            ossClient.shutdown();
        }
        return null;
    }

    @Override
    public void delOssUrls(OSSDelModel delModel, FileOSSModel ossModel) {
        OSSClient ossClient = initOSSClient(ossModel);
        try {
            ossClient.deleteObjects(new DeleteObjectsRequest(ossModel.getBucketName()).withKeys(delModel.getImgUrls()).withEncodingType("url"));
        }catch ( Exception e){
            logger.error("阿里云OSS删除文件失败:",e);
        }finally {
            ossClient.shutdown();
        }
    }

    @Override
    public String generatePresignedUrl(OSSUrlModel urlModel, FileOSSModel ossModel) {
        OSSClient ossClient = initOSSClient(ossModel);
        try {
            String url = urlModel.getFileUrl().substring(1);
            URL urls = ossClient.generatePresignedUrl(ossModel.getBucketName(), url, DateUtil.addMinute(new Date(), 300));
            return ossModel.getCurl()+urls.getFile();
        }catch ( Exception e){
            logger.error("阿里云OSS生成预签名失败:",e);
        }finally {
            ossClient.shutdown();
        }
        return null;
    }

    public OSSClient initOSSClient(FileOSSModel ossModel){
        OSSClient ossClient = new OSSClient(ossModel.getEndpoint(), ossModel.getAccessKeyId(), ossModel.getAccessKeySecret());
        return ossClient;
    }

    @Override
    public String videoFirstFrame(OSSUrlModel urlModel, FileOSSModel ossModel) {
        // 创建OSSClient实例
        OSS ossClient = initOSSClient(ossModel);
        try {
            // 设置签名URL过期时间(1小时后过期)
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
            // 创建生成签名URL请求
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(ossModel.getBucketName(), urlModel.getFileUrl().substring(1));
            request.setExpiration(expiration);
            // 添加图片处理参数
            request.setProcess("video/snapshot,t_1000,m_fast");
            // 生成签名URL
            URL signedUrl = ossClient.generatePresignedUrl(request);
            return ossModel.getCurl()+signedUrl.getFile();
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }
}
